package cn.hl.hm.service.impl;

import cn.hl.hm.dao.*;
import cn.hl.hm.entity.*;
import cn.hl.hm.service.DriverService;
import cn.hl.hm.util.UUID;
import cn.hl.hm.util.paging.PageInfo;
import com.vizhuo.utils.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@Service
public class DriverServiceImpl implements DriverService {
	@Autowired
	private DriverMapper driverMapper;
	@Autowired
	private HotDetailMapper hotDetailMapper;
	@Autowired
	private HotMapper hotMapper;
	@Autowired
	private WithdrawApplyMapper withdrawApplyMapper;
	@Autowired
	private RechargeRecoardMapper rechargeRecoardMapper;
	private static final Logger logger = LoggerFactory.getLogger(DriverServiceImpl.class);
	
	private final static SimpleDateFormat hhmmSdf = new SimpleDateFormat("yyyy-MM-dd");

	@Override
	public int deleteByPrimaryKey(Integer id) {
		return driverMapper.deleteByPrimaryKey(id);
	}

	@Override
	public int insert(Driver record) {
		return driverMapper.insert(record);
	}

	@Override
	public int insertSelective(Driver record) {
		return driverMapper.insertSelective(record);
	}

	@Override
	public Driver selectByPrimaryKey(Integer id) {
		return driverMapper.selectByPrimaryKey(id);
	}

	@Override
	public int updateByPrimaryKeySelective(Driver record) {
		return driverMapper.updateByPrimaryKeySelective(record);
	}

	@Override
	public int updateByPrimaryKey(Driver record) {
		return driverMapper.updateByPrimaryKey(record);
	}

	@Override
	public List<Driver> selectDriver(Driver driver) {
		return driverMapper.selectDriver(driver);
	}

	/**
	 * @Title: addHotRecord @author: 星矢 @date :2017年1月4日 @Description: TODO @throws
	 */
	@Transactional
	public int addHotRecord(Integer driverId, String role, String oper) {
		int i = 0;
		Date date = new Date();
		String now = new SimpleDateFormat("yyyy-MM-dd").format(date);
		HotDetail thd = new HotDetail();
		thd.setCreateTime(date);
		thd.setType(role);
		thd.setOperate(oper);
		thd.setUserId(driverId);
		i = hotDetailMapper.insertSelective(thd);

		Hot hot = hotMapper.selectByTime(now);
		if (hot != null) {
			if (role.equals("1")) {// 用户
				hot.setDriverAmount(hot.getDriverAmount() + 1);

			} else {// 司机
				hot.setDriverAmount(hot.getDriverAmount() + 1);
			}
			// 更新+1
			hot.setUpdateTime(date);
			i = hotMapper.updateByPrimaryKeySelective(hot);
		} else {
			Hot record = new Hot();
			if (role.equals("1")) {// 用户
				record.setDriverAmount(0);
				record.setDriverAmount(1);

			} else {// 司机
				record.setDriverAmount(0);
				record.setDriverAmount(1);

			}
			record.setUpdateTime(date);
			record.setCreateTime(date);
			i = hotMapper.insert(record);
		}
		return i;

	}

	@Override
	@Transactional
	public int addDriver(Driver driver) {
		return driverMapper.insertSelective(driver);
	}

	// @Override
	// public int updateDriver(Driver driver) {
	// synchronized(lock) {
	// return driverMapper.updateByPrimaryKeySelective(driver);
	// }
	//
	// }
	@Override
	public int updateDriver(Driver driver) {

		return driverMapper.updateByPrimaryKeySelective(driver);

	}

	@Override
	public List<Driver> selectDriverInfo(Driver driver) {
		// TODO Auto-generated method stub
		return driverMapper.selectDriverInfo(driver);
	}

	@Override
	public OrderVO selectOrderOtherInfo(Integer driverId) {
		// TODO Auto-generated method stub
		return driverMapper.selectOrderOtherInfo(driverId);
	}

	@Override
	public List<Driver> selectDriverInfoForVehiclePrice(Driver driver) {
		// TODO Auto-generated method stub
		return driverMapper.selectDriverInfoForVehiclePrice(driver);
	}

	@Override
	public DriverAmountInfo selectDriverHistory(Integer driverId) {
		// TODO Auto-generated method stub
		return driverMapper.selectDriverHistory(driverId);
	}

	@Transactional
	public int addApply(WithdrawApply withdrawApply) {
		Driver driver1 = driverMapper.selectByPrimaryKey(withdrawApply.getDriverId());
		if (driver1 == null) {
			return 0;
		}
		BigDecimal remainCash = driver1.getRemainCash();
		String randomNumberUUID = UUID.randomNumberUUID(18);
		// 申请
		withdrawApply.setWithdrawCode(randomNumberUUID);
		withdrawApply.setRemainCash(remainCash);
		withdrawApply.setIdCardNum(driver1.getIdCard());
		withdrawApply.setDriverPhone(driver1.getDriverPhone());
		withdrawApply.setPlateNumber(driver1.getPlateNumber());
		withdrawApply.setCreateTime(new Date());
		int insertSelective = withdrawApplyMapper.insertSelective(withdrawApply);
		if (insertSelective > 0) {

			RechargeRecoard rr = new RechargeRecoard();
			rr.setOperType(3);// 退款
			rr.setStatus("1"); // 设置消费状态 （1 退款中 2 退款成功 3退款失败）
			rr.setCreateTime(new Date());
			rr.setDriverId(withdrawApply.getDriverId());

			rr.setRemainCash(remainCash);
			rr.setUserphone(withdrawApply.getDriverPhone());
			BigDecimal withdrawCash = withdrawApply.getWithdrawCash();
			rr.setAmount(withdrawCash);
			rr.setRechargeCode(randomNumberUUID);
			rr.setWithdrawBankCardNum(withdrawApply.getWithdrawBankCardNum());
			int addRechargeRecoard = rechargeRecoardMapper.insertSelective(rr);
			if (addRechargeRecoard > 0) {
				// 司机表
				Driver driver = new Driver();
				BigDecimal realWith = driver1.getWithdrawCash().add(withdrawCash);
				driver.setWithdrawCash(realWith);
				driver.setId(withdrawApply.getDriverId());
				int up1 = driverMapper.updateByPrimaryKeySelective(driver);
				if (up1 > 0) {
					return 1;
				} else {
					return 0;
				}
			} else {
				return 0;
			}
		} else {
			return 0;
		}

	}

	@Transactional
	public int auditApply(WithdrawApply param) {
		int i = 0;
		WithdrawApply wApply = withdrawApplyMapper.selectByPrimaryKey(param.getId());
		if (wApply == null||wApply.getDriverId()==null) {
			return i;
		}
		// 司机账户
		
		DriverAmountInfo driverInfo = selectDriverHistory(wApply.getDriverId());
		if(driverInfo==null) {
			return i ;
		}
		BigDecimal remainCash = driverInfo.getRemainCash();//司机余额 
		BigDecimal withdrawCashing = wApply.getWithdrawCash();//当前提现
		BigDecimal allwithdrawCash = driverInfo.getWithdrawCash();//累计提现（包括本次）
		BigDecimal unsubedRewardCash = driverInfo.getUnsubedRewardCash();//未扣减奖励金额
		if(allwithdrawCash.compareTo(remainCash)>0) {
			logger.info("司机id："+wApply.getDriverId()+"累计正提现金额"+allwithdrawCash+"大于余额"+remainCash+"请核实");
			return i;
		}
		int paramStatus = Integer.parseInt(param.getWithdrawStatus());// 参数
		int dbStatus = Integer.parseInt(wApply.getWithdrawStatus());// 实际
		if (paramStatus <= dbStatus) {// 退款状态：1，审核中，2，退款成功，3，退款失败
			logger.info("司机id："+wApply.getDriverId()+"提现状态不可逆");
			return i;
		}else {
			
		}
		WithdrawApply w = new WithdrawApply();
		w.setId(param.getId());
		w.setWithdrawStatus(param.getWithdrawStatus());
		w.setUpdateTime(new Date());
		w.setOpenUser(param.getOpenUser());
		int updateByPrimaryKey = withdrawApplyMapper.updateByPrimaryKeySelective(w);

		if (updateByPrimaryKey > 0) {
			// 操作记录
			RechargeRecoard rr = new RechargeRecoard();
			rr.setOperType(3);// 退款
			rr.setStatus(param.getWithdrawStatus()); // 设置消费状态 （1 退款中 2 退款成功 3退款失败）
			rr.setCreateTime(new Date());
			rr.setDriverId(wApply.getDriverId());
			rr.setRemainCash(remainCash);
			rr.setUserphone(wApply.getDriverPhone());
			rr.setAmount(withdrawCashing);
			rr.setRechargeCode(wApply.getWithdrawCode());
			rr.setWithdrawBankCardNum(wApply.getWithdrawBankCardNum());
			int addRechargeRecoard = rechargeRecoardMapper.insertSelective(rr);
			if (addRechargeRecoard > 0) {
				
				Driver d = new Driver();
				d.setId(wApply.getDriverId());
				BigDecimal realWithdraw = allwithdrawCash.subtract(withdrawCashing);// 实际剩余提现余额
				if(paramStatus==2) {//审核通过
					//可提现金额 = 总充（包括奖励）-已奖励-已消费-已提现-正在提现
					//实际可用余额=总充（包括奖励）-已消费-已提现
					//首次提现清空剩余奖励金额
					
					remainCash = remainCash.subtract(withdrawCashing);//减去本次提现
					if(unsubedRewardCash.compareTo(new BigDecimal(0))<=0) {
						
						d.setRemainCash(remainCash);
						d.setWithdrawCash(realWithdraw);
						int updateByPrimaryKeySelective = driverMapper.updateByPrimaryKeySelective(d);
						if (updateByPrimaryKeySelective > 0) {
							//logger.info(msg);
							i = 1;
							return i;
						} else {
							return i;
						} 
					}else {
						BigDecimal withdrawAfterReaminCash_conclude = remainCash;////减去本次提现
						if(remainCash.compareTo(unsubedRewardCash)<0) {
							remainCash = new BigDecimal(0);
							unsubedRewardCash = remainCash;

						}else {
							BigDecimal subtract = remainCash.subtract(unsubedRewardCash);
							remainCash = subtract;
						}
					
						RechargeRecoard  r= new RechargeRecoard();
						r.setOperType(4);// 扣除奖励
						r.setStatus("2"); // 设置消费状态 （1 退款中 2 退款成功 3退款失败）
						r.setCreateTime(new Date());
						r.setDriverId(wApply.getDriverId());
						r.setRemainCash(withdrawAfterReaminCash_conclude);
						r.setUserphone(wApply.getDriverPhone());
						r.setAmount(unsubedRewardCash);
						r.setRechargeCode(wApply.getWithdrawCode());
						r.setWithdrawBankCardNum(wApply.getWithdrawBankCardNum());
						int result = rechargeRecoardMapper.insertSelective(r);
						if(result>0) {
							d.setRemainCash(remainCash);
							d.setWithdrawCash(realWithdraw);
							int updateByPrimaryKeySelective = driverMapper.updateByPrimaryKeySelective(d);
							if (updateByPrimaryKeySelective > 0) {
								//logger.info(msg);
								i = 1;
								return i;
							} else {
								return i;
							} 
						}else {
							return i;
						}
					}
					
				}else {
					//不通过，不更新余额 
					d.setWithdrawCash(realWithdraw);
					int updateByPrimaryKeySelective = driverMapper.updateByPrimaryKeySelective(d);
					if (updateByPrimaryKeySelective > 0) {
						//logger.info(msg);
						i = 1 ;
						return i;
					} else {
						return i;
					} 
				}
			} else {
				return i;
			}
		} else {
			return i;
		}

	}

	@Override
	public List<WithdrawApply> getApply(Integer driverId) {
		WithdrawApply withdrawApply = new WithdrawApply();
		withdrawApply.setDriverId(driverId);
		withdrawApply.setWithdrawStatus("1");
		List<WithdrawApply> selectWithdrawApply = withdrawApplyMapper.selectWithdrawApply(withdrawApply);
		
		return selectWithdrawApply;
	}

	@Override
	public List<Driver> selectDriverInfoListPage(PageInfo pageInfo) {
		return driverMapper.selectDriverInfoListPage(pageInfo);
	}

	@Override
	public List<Driver> selectListByIds(List<Integer> ids) {
		if (ids==null || ids.isEmpty()) {
			return null;
		}
		return driverMapper.selectListByIds(ids);
	}

	@Override
	public void fillChargeSetting(List<Driver> ddlList) {
		for (Driver driver2 : ddlList) {
			if (driver2.getNoloadFree().equals(1)) {
				driver2.setChargeSetting("空载免收");
			}else{
				if(driver2.getIsSecurity().equals("0")) {
					if(driver2.getFreeTime()!=null) {
						String format = hhmmSdf.format(new Date());
						Date nowDate =DateUtil.string2DateNoTime(format);
						String format2 = hhmmSdf.format(driver2.getFreeTime());
						Date driverDate =DateUtil.string2DateNoTime(format2);
						if(driverDate.getTime()>=nowDate.getTime()) {
							driver2.setIsSecurity("2");
							Calendar cal = Calendar.getInstance();
							cal.setTime(nowDate);
							long time1 = cal.getTimeInMillis();

							cal.setTime(driverDate);
							long time2 = cal.getTimeInMillis();
							int between_days=(int) ((time2-time1)/(1000*3600*24));
							driver2.setFreeDay(Integer.parseInt(String.valueOf(between_days))+1);
							driver2.setChargeSetting("免费至"+ DateUtil.date2StringNoTime(driver2.getFreeTime()));
						}else {
							driver2.setChargeSetting("永久收费");
							driver2.setFreeTime(null);
							driver2.setFreeDayFlag(1);
							updateDriver(driver2);
						}

					}else {
						driver2.setChargeSetting("永久收费");
					}
				}else {
					driver2.setChargeSetting("永久免费");
				}
			}
		}
	}
}
